# 项目初始化文件【创建App应用对象的函数，各种模块初始化】
from fastapi import FastAPI
from dotenv import load_dotenv
from tortoise.contrib.fastapi import register_tortoise
from . import settings
from .apps.common.views import app as common_app
from .apps.users.views import app as users_app
from .utils import middleware,exception  #日志中间件
import os

def create_app() -> FastAPI:
    """创建web应用对象"""
    load_dotenv()     # 加载.env文件中的环境变量

    app: FastAPI = FastAPI(
        #注册异常组件
        exception_handlers={
               exception.HTTPException:exception.global_exception_handler,
               exception.RequestValidationError:exception.global_requests_exception

        }
    )


    # 把Tortoise-orm注册到App应用对象中
    register_tortoise(
        app,
        config=settings.TORTOISE_ORM,
        generate_schemas=False,  # 是否自动生成表结构
        add_exception_handlers=True,  # 是否启用自动异常处理
    )

    # 注册各个应用分组下的路由信息，合并到App应用对象  代表路径前缀
    app.include_router(common_app, prefix='')
    app.include_router(users_app, prefix='/users')

    # 注册中间件函数
    http_middleware = app.middleware('http')
    http_middleware(middleware.log_requests)  #日志中间件

    return app